use mysql::*;
use mysql::prelude::*;
//文档:https://docs.rs/mysql/21.0.1/mysql/

//数据库连接配置Opts
#[test]
pub fn opts_demo(){
   /* let _ = Opts::from_url("mysql://localhost/some_db")?;
    let _ = Opts::from_url("mysql://[::1]/some_db")?;
    let _ = Opts::from_url("mysql://user:pass%20word@127.0.0.1:3307/some_db?")?;

    let opts = OptsBuilder::new()
        .ip_or_hostname(Some("192.168.56.101"))
        .user(Some("root"))
        .pass(Some("denglibin"))
        .db_name(Some("denglibin"));
    let _ = Conn::new(opts)?;*/
}

//查询
#[test]
pub fn mysql_demo(){
    //设置连接字符串
    let url=r"mysql://root:denglibin@192.168.56.101:3306/denglibin";

    //创建连接池
    let pool=Pool::new(Opts::from_url(url).unwrap()).unwrap();

    //获取连接
    let mut conn=pool.get_conn().unwrap();

    //1.查询user表
    //方式1：流式查询  数据逐行读取，数据不会存储在内存中
    conn.query_iter("Select id,username from user").unwrap()
        .for_each(|row|{
            let r:(i32, String)=from_row(row.unwrap());
            println!("id={},username={}", r.0, r.1);
        });

    //方式2：将数据集取出存储在Vec中
    let res:Vec<(i32, String)> = conn.query("Select id,username from user").unwrap();
    for r in res{
        println!("id={},username={}",r.0, r.1);
    }

    //方式3：将数据转换成Struct
    struct User{
        id: i32,
        username: String,
    }
    let res=conn.query_map("Select id, username from user",
                           |(id, username)|User{
                               id,
                               username,
                           }
    ).expect("QUERY FAILED");
    for user in res{
        println!("id={},username={},", user.id, user.username);
    }
}

